const path = require('path')
const webpack = require('webpack')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const TsconfigPathsWebpackPlugin = require('tsconfig-paths-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const nestCliJson = require('./nest-cli.json')

const tsConfigFile = path.resolve(__dirname, 'tsconfig.build.json')
const lazyImports = [
  '@nestjs/microservices',
  '@nestjs/microservices/microservices-module',
  '@nestjs/websockets/socket-module',
  'class-transformer/storage',
  '@fastify/static',
  '@nestjs/platform-socket.io',
]

module.exports = {
  entry: path.resolve(nestCliJson.sourceRoot, 'main.ts'),
  target: 'node',
  mode: 'production',
  // 置为空即可忽略webpack-node-externals插件
  externals: {},
  // externalsPresets: { node: true },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: {
          loader: 'ts-loader',
          options: {
            transpileOnly: true,
            configFile: tsConfigFile,
          },
        },
        exclude: /node_modules/,
      },
    ],
  },
  // 打包后的文件名称以及位置
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist/apps/app'),
  },
  resolve: {
    alias: {
      'html-parse-stringify': path.resolve(__dirname, 'vendors/html-parse-stringify.js'),
    },
    extensions: ['.js', '.ts', '.tsx', '.json'],
    plugins: [
      new TsconfigPathsWebpackPlugin({
        configFile: tsConfigFile,
      }),
    ],
  },
  optimization: {
    minimize: false,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          keep_classnames: true,
          keep_fnames: true,
        },
      }),
    ],
  },
  plugins: [
    // 需要进行忽略的插件
    new webpack.IgnorePlugin({
      checkResource(resource) {
        if (lazyImports.includes(resource)) {
          try {
            require.resolve(resource)
          } catch (err) {
            return true
          }
        }
        return false
      },
    }),
    new ForkTsCheckerWebpackPlugin({
      typescript: {
        configFile: tsConfigFile,
      },
    }),
  ],
}
